/*
 * contextswitch.c
 *
 *  Created on: 14.10.2013
 *      Author: rop
 */
#include <stdlib.h>
#include <ucontext.h>
#include <stdio.h>

#define N 1000
#define STACK_SIZE 16384
unsigned long count = 100000;

ucontext_t us[N];

char stacks[STACK_SIZE * N];

void f(int self_id) {
	int next_id = (self_id + 1) % N;
	ucontext_t *self = us + self_id;
	ucontext_t *next = us + next_id;
	volatile unsigned long *cnt = &count;
	while (--*cnt > 0) {
		printf("self_id: %d, cnt: %ld\n", self_id, *cnt);
		if (swapcontext(self, next) == -1) {
			printf("error\n");
			exit(-1);
		}
	}
}
int main(void) {

	ucontext_t u0;
	int i;
	i = 0;
	for (i = 0; i < N; i++) {
		ucontext_t *u = us + i;
		if (getcontext(u) == -1)
			exit(-1);
		u->uc_stack.ss_sp = &stacks[i * STACK_SIZE];
		u->uc_stack.ss_size = STACK_SIZE;
		u->uc_link = &u0;
		makecontext(u, (void (*)(void)) f, 1, i);
	}
	swapcontext(&u0, &us[0]);
	printf("exit");
	return 0;
}
